<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/16 0016
 * Time: 15:16
 */

namespace Home\Controller;

class OrderController extends CommonController
{
    function __construct()
    {
        parent::__construct();
        $this->customer_id = $_SESSION['customer']['id'];
    }

    public function index()
    {

        //查出用户的收货地址
        $address = $this->address->where("customer_id = $this->customer_id")->find();

        //查出用户所有的商品
        $products = $this->cart->alias('a')->field('a.id as cart_id,a.num,b.*')
            ->join('product as b ON b.id=a.product_id', 'LEFT')
            ->where(['a.customer_id' => $this->customer_id])->select();
        //商品总价
        $total = 0;
        foreach ($products as $k => $v) {
            $total += floatval($v['price']) * intval($v['num']);
        }

        $this->assign(compact('address', 'products', 'total'));
        $this->display();
    }

    /***
     * 新增收货地址
     * 注：如果用户已经有了地址，只需更新用户的地址
     */
    public function add_address()
    {
        if (IS_AJAX) {
            $data['customer_id'] = $this->customer_id;
            $data['name'] = I('post.name');
            $data['tel'] = I('post.tel');
            $area = I('post.area');
            $address = I('post.address');
            $data['address'] = $area . ' ' . $address;
            $res = $this->address->where("customer_id = $this->customer_id")->find();
            if ($res) {
                $this->address->where("customer_id = $this->customer_id")->save($data);
            } else {
                $this->address->where("customer_id = $this->customer_id")->add($data);

            }
        }
    }

    /***
     * 立即支付（即下单）
     * 需求：订单数据插入订单表，订单商品数据插入订单商品表，
     *     1.下单时后台判断商品库存是否充足；
     *     2.对应减去商品的库存及清空购物车并记录商品已售数量；
     *     3：跳转
     */
    public function store()
    {
        //dump($_POST);exit;
        //连表（a:cart表；b：product表）查出商品信息
        $products = $this->cart->alias('a')->field('a.id as cart_id,a.num,b.*')
            ->join('product as b ON b.id=a.product_id', 'LEFT')
            ->where(['a.customer_id' => $this->customer_id])->select();

        $total = 0;
        foreach ($products as $k => $v) {
            $total += floatval($v['price']) * intval($v['num']);
            //判断商品库存是否充足
            if (intval($v['num']) > intval($v['stock'])) {
                $this->error('此商品库存不足');
            }
        }

        //生成订单
        $data = [];
        $data['customer_id'] = $this->customer_id;
        $data['order_no'] = make_token_code();
        $data['address_id'] = I('post.address_id');
        $data['total_price'] = $total;
        $data['create_at'] = time();
        $data['status'] = 1;//默认状态为1；
//        dump($data);exit;
        //把订单数据插入订单表
        $id = $this->order->add($data);
        if ($id) {
            $orderproductInfo['order_id'] = $id;
            //订单商品数据插入订单商品表
            foreach ($products as $k => $v) {
//                dump($products);exit;
                $orderproductInfo['product_id'] = $v['id'];
                $orderproductInfo['number'] = $v['num'];
                $this->order_product->add($orderproductInfo);
            }
            //支付成功后对应减去商品库存并且清空购物车
            $numbers = intval($orderproductInfo['number']);
            $product_id = $orderproductInfo['product_id'];
//            $this->product->where("id = '$product_id'")->setField('sale_done', $numbers);//已售商品数量
            $this->product->where("id = '$product_id'")->setDec('stock', $numbers);//减去库存
            $this->cart->where("customer_id = $this->customer_id")->delete();//清空购物车
            $info = array('status' => 1, 'msg' => '您已成功下单');

        } else {
            $info = array('status' => 1, 'msg' => '下单失败');
        }
        $this->ajaxReturn($info);
    }
}